package cn.jwtool.jwcache.thread;

import org.reflections.Reflections;

import java.lang.reflect.Method;

/**
 * @author : willian fu
 * @version : 1.0
 */
public class TimerInit {
    public TimerInit(){
        init();
    }
    private void init(){
        Reflections reflections = new Reflections();
        reflections.getTypesAnnotatedWith(Timer.class).forEach(clazz -> {
            try {
                for (Method method : clazz.getMethods()) {
                    Timer timer = method.getAnnotation(Timer.class);
                    if (null != timer){
                        Object obj = clazz.newInstance();
                        if (timer.type()){
                            //循环任务
                            TaskManager.executorLoopTask(()->{
                                try {
                                    method.invoke(obj);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    System.err.println("@Timer 注解的方法 " + method.getName() + " 反射调用失败");
                                }
                            }, timer.value(), timer.unit());
                        }else {
                            //定时一次性任务
                            TaskManager.executorDelayTask(()->{
                                try {
                                    method.invoke(obj);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    System.err.println("@Timer 注解的方法 " + method.getName() + " 反射调用失败");
                                }
                            }, timer.value(), timer.unit());
                        }
                    }
                }
            } catch (InstantiationException | IllegalAccessException e) {
                e.printStackTrace();
            }
        });
    }
}
